/*
 *@项目名称：智慧供热平台之换热站子系统
 *@模块名称：TODO
 *@包名：(#)com.b505.system.security
 *@文件名：KaptchaAuthenticationFilter.java
 *@创建时间:2018年8月5日下午2:01:38
 *@作者：ASUS
 *@Copyright 2009-2018 shannon智慧物联科技
 */

package com.sjy.security;

import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import com.google.code.kaptcha.Constants;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @类名：KaptchaAuthenticationFilter 
 * @author ：陈挺，2018年8月5日
 * @修改者：
 * @功能描述：验证码过滤器，在验证用户名密码之前进行对验证码的判断，失败就报出输入的验证码不正确的错误
 */

public class KaptchaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	 private String servletPath;
	    public KaptchaAuthenticationFilter(String servletPath, String failureUrl) {
	        super(servletPath);
	        this.servletPath = servletPath;
	        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
	    }
	    @Override
	    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	        HttpServletRequest req = (HttpServletRequest) request;
	        HttpServletResponse res = (HttpServletResponse) response;
	        if ("POST".equalsIgnoreCase(req.getMethod()) && servletPath.equals(req.getServletPath())) {
	            String expect = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	            if (expect != null && !expect.equalsIgnoreCase(req.getParameter("kaptcha"))) {
	                unsuccessfulAuthentication(req, res, new InsufficientAuthenticationException("输入的验证码不正确"));
	                return;
	            }
	        }
	        chain.doFilter(request, response);
	    }
	    @Override
	    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
	        return null;
	    }
}
